package com.qhx.rtkcloud.tcp;

//import javafx.util.Pair;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.Socket;
import java.util.List;

@Component
@Profile({"tcpclient"})
@ConfigurationProperties(prefix = "tcp.exchange")
@Configuration
public class TcpClientExchangePair extends TcpExchangePair implements InitializingBean {

//    private Pair<String, Integer> getIpAndPort(String ipAndPort) {
//        int colon = ipAndPort.indexOf(":");
//        if (colon == -1 && ipAndPort.matches("-?\\d+(\\.\\d+)?")) { // 只有端口
//            return new Pair<>(null, Integer.parseInt(ipAndPort));
//        }
//
//        if (colon > 0) {
//            String ip = ipAndPort.substring(0, colon);
//            int port = Integer.parseInt(ipAndPort.substring(colon + 1));
//            return new Pair<>(ip, port);
//        }
//        return null;
//    }

    private void reConnect(String host, int port) {
        TcpExchangeUnit tcpExchangeUnit = TcpExchangeUnit.TCP_EXCHANGE_UNIT_THREAD_LOCAL.get();
        if (tcpExchangeUnit == null) {
            return;
        }
        connectServer(host, port, tcpExchangeUnit);
        TcpExchangeUnit.TCP_EXCHANGE_UNIT_THREAD_LOCAL.remove();

    }


    private void doConnectServer(String host, Integer port, TcpExchangeUnit tcpExchangeUnit) {
        Socket client = null;

        try {
            client = new Socket(host, port);
        } catch (IOException e) {
            connectServer(host, port, tcpExchangeUnit);
        }
        Thread.setDefaultUncaughtExceptionHandler((t, e) -> {//  start 方法线程中出现异常 需要重连
          String message = e.getMessage();
          String[] params = message.split(":");
            if (params.length == 3) {
                reConnect(params[1], Integer.valueOf(params[2]));
            }
            e.printStackTrace();
        });

        if (client == null) {
            return;
        }
        tcpExchangeUnit.setClient(client);
        tcpExchangeUnit.start();
    }

    // 需要在断开的时候重新调用
    private void connectServer(String host, Integer port, TcpExchangeUnit tcpExchangeUnit) {
        // 先判断是不是可以发起连接
        synchronized (tcpExchangeUnit.isConnectFreedom() ? tcpExchangeUnit.connectLock : tcpExchangeUnit.getPartner().connectLock) {
            if (tcpExchangeUnit.isConnectFreedom()
                    && !tcpExchangeUnit.getPartner().isConnectFreedom()
                    && tcpExchangeUnit.getPartner().getClient() != null
                    && !tcpExchangeUnit.getPartner().getClient().isClosed()) {
                try {
                    tcpExchangeUnit.getPartner().getClient().close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            /**
             * 有漏洞先忽略
             */
            doConnectServer(host, port, tcpExchangeUnit);
        }
    }

    //    @Override
    protected void setSocket(String host, int port, TcpExchangeUnit tcpExchangeUnit) {

        connectServer(host == null ? "127.0.0.1" :host, port, tcpExchangeUnit);


    }


}
